/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务                                                   
*│　作    者：sys                                              
*│　创建时间：2020-12-02 14:55:26   
*│　说    明：代码生成器生成   
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using Dapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using NPOI.SS.Formula.Functions;
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Model.SysOrganizeUser;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
	/// SysUser服务层
	/// </summary>
    public class SysUserService : ISysUserService
    {
        private readonly ISysUserRepository _repository;
        private readonly ISysUserRoleRepository _sysUserRoleRepository;
        private readonly ISysOrganizeRepository _OrgRepository;
        private readonly ISysOrganizeUserRepository _orgUserRepository;
        private readonly IMapper _mapper;
        private readonly ICache _cache;
        private readonly ISysPermissionRepository _permissonRepository;
        private readonly IDbContext _dbContext;
        private readonly ILoginInfo _loginInfo;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly FileUploadHelper _uploadHelper;

        public SysUserService(ISysUserRepository repository, ISysUserRoleRepository sysUserRoleRepository,IMapper mapper,ICache cache,ISysPermissionRepository sysPermissionRepository,ISysOrganizeRepository sysOrganizeRepository,ISysOrganizeUserRepository sysOrganizeUserRepository,IDbContext dbContext,ILoginInfo loginInfo,IWebHostEnvironment webHostEnvironment,FileUploadHelper fileUploadHelper)
        {
            _uploadHelper = fileUploadHelper;
            _webHostEnvironment = webHostEnvironment;
            _loginInfo = loginInfo;
            _dbContext = dbContext;
            _orgUserRepository = sysOrganizeUserRepository;
            _OrgRepository = sysOrganizeRepository;
            _permissonRepository = sysPermissionRepository;
            _cache = cache;
            _mapper = mapper;
            _sysUserRoleRepository = sysUserRoleRepository;
            _repository = repository;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        public async Task<IApiResult> Add(UserAddModel model)
        { 
            ////工作单元处理事务
            //var uow = _dbContext.NewUnitOfWork();
            //try
            //{
                model.PassWord = Md5Encrypt.Encrypt(model.PassWord);
                var entity = _mapper.Map<SysUserEntity>(model);
            //判断用户名是否重复
            var res = await _repository.ExistsAsync(entity.UserName, "SysUser", "UserName");
            if (res)
                return ApiResult.NotOk("用户名重复，已经存在此用户名的账号！");
            entity.Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
                entity.Deleted = 0;
                entity.CreateTime = DateTime.Now;

                var res2 = await _repository.InsertAsync(entity);
                
                if (res2.NotNull())
                {
              
                    if (model.Roles.Any())
                    {
                        var roles = model.Roles.Select(a => new SysUserRoleEntity { SysUserId = entity.Id, SysRoleId = a });
                        await _sysUserRoleRepository.InsertAsync(roles);
                    }

                //添加组织关系
                if (model.OrganizeId.NotNull())
                {
                    ////查询出当前部门的所有父级部门
                    //var listOrg = await _OrgRepository.GetParents(model.OrganizeId);
                    //var list_add = new List<SysOrganizeUserEntity>();
                    //foreach (var item in listOrg)
                    //{
                    //    SysOrganizeUserEntity data = new SysOrganizeUserEntity { SysUserId = entity.Id, SysOrganizeId = item.Id };
                    //    list_add.Add(data);
                    //}
                    SysOrganizeUserEntity data = new SysOrganizeUserEntity { SysUserId = entity.Id, SysOrganizeId = model.OrganizeId };
                    //批量插入数据到[SysOrganizeUser]
                    await _orgUserRepository.InsertAsync(data);
                }


            }
            return ApiResult.Ok();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<IApiResult> Query(UserQueryModel model)
        {
            var result = new PageResult<SysUserEntity>
            {
                Rows = await _repository.Query(model),
                TotalCount = model.TotalCount
            };
            foreach (var item in result.Rows)
            {
                var roles = await _sysUserRoleRepository.QueryRole(item.Id);
                item.Roles = string.Join(",", roles.Where(a=>a.Selected==true).Select(t => t.Name).Distinct().ToArray());
            }
            return ApiResult.Ok(result);
        }

        public async Task<List<string>> QueryPermissionList(string userId)
        {
            var account = await Get(userId);
            if (account == null || account.Deleted==1)
                return new List<string>();

            var key = string.Format(CacheKey.USER_PERMISSIONS, userId);
            if (!_cache.TryGetValue(key, out List<string> list))
            {
                list = await _permissonRepository.QueryCodeByUserId(userId);
                await _cache.SetAsync(key, list);
            }
            return list;
        }
        public async Task<SysUserEntity> Get(string userId)
        {
            //先从缓存取 缓存没有再查询
            var key = string.Format(CacheKey.USER, userId);
            if (_cache.TryGetValue(key, out SysUserEntity account))
                return account;

            account = await _repository.GetAsync(userId);
            if (account != null)
            {
                await _cache.SetAsync(key, account);
            }

            return account;
        }

        public async Task<IApiResult> Delete(List<string> ids)
        {
            //if (ids.IsNull()) return ApiResult.NotOk("参数【ids】错误");
            //var idArr = ids.Split(',');

            var res = await _repository.DeleteManyAsync(ids, "sysuser");
            if (res>0)
                return ApiResult.Ok(res,"成功删除"+res+"条数据");
            else
                return ApiResult.NotOk("删除失败");
        }
        public async Task<IApiResult> Update(UserUpdateModel model)
        {
            var entity = _mapper.Map<SysUserEntity>(model);
      
            var res = await _repository.UpdateAsync(entity);
           
            if (res)
            {
                //更新角色
                if (model.Roles.Any())
                {
                    //删除当前用户所有的角色信息
                    var count = await _sysUserRoleRepository.DeleteUserId(entity.Id);
                    var roles = new List<SysUserRoleEntity>();
                    foreach (var item in model.Roles)
                    {
                           roles.Add(new SysUserRoleEntity { SysUserId = entity.Id, SysRoleId = item });
                    }
                  
                    await _sysUserRoleRepository.InsertAsync(roles);
                }
                //添加组织关系
                if (model.OrganizeId.NotNull())
                {
                    //删除SysOrganizeUser表中该用户的记录
                    await _orgUserRepository.DeleteByUserId(entity.Id);

                    ////查询出当前部门的所有父级部门
                    //var listOrg = await _OrgRepository.GetParents(model.OrganizeId,null);
                    //var list_add = new List<SysOrganizeUserEntity>();
                    //foreach (var item in listOrg)
                    //{

                    //  SysOrganizeUserEntity data = new SysOrganizeUserEntity { SysUserId = entity.Id, SysOrganizeId = item.Id };
                    //  list_add.Add(data);
                    //}
                    SysOrganizeUserEntity data = new SysOrganizeUserEntity { SysUserId = entity.Id, SysOrganizeId = model.OrganizeId };
                    //批量插入数据到[SysOrganizeUser]
                    await _orgUserRepository.InsertAsync(data);

                }
                return ApiResult.Ok("修改成功");
            }
            else
            {
                return ApiResult.NotOk("修改失败");
            }   
           
              
        }

        public async Task<IApiResult> GetById(string id)
        {
            var entity = await _repository.GetAsync(id);
            if (entity == null)
                return ApiResult.NotOk("账户不存在");

            var model = _mapper.Map<UserUpdateModel>(entity);
            var all = await _orgUserRepository.GetAllAsync();
            model.OrganizeId = all.Where(a => a.SysUserId == id).Select(b => b.SysOrganizeId).FirstOrDefault();
            var roles = await _sysUserRoleRepository.QueryRole(id);
            model.Roles = roles.Where(a => a.Selected == true).Select(t => t.Id).Distinct().ToList(); ;
            var org = await _OrgRepository.GetAsync(model.OrganizeId);
            model.OrganizeName =org?.Name;
            return ApiResult.Ok(model);
        }

        public async Task<IApiResult> SyncUser()
        {
            var user = new SysUserEntity()
            {
                Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd),
                TrueName = "舒",
                UserName = "shuyuansong",
                Password = "123456"
            };

            return ApiResult.Ok( await _repository.InsertAsync(user));
          
            //return ApiResult.Ok();
        }

        public async Task<IApiResult> EditPwd(string oldpwd, string newpwd)
        {
            //先判断oldpwd是否正确
            var user = await _repository.GetAsync(_loginInfo.UserId);
            if (!user.Password.Equals(Md5Encrypt.Encrypt(oldpwd),StringComparison.CurrentCultureIgnoreCase))
            {
                return ApiResult.NotOk("原始密码不匹配，修改失败");
            }
            user.Password = Md5Encrypt.Encrypt(newpwd);
            var res= await _repository.UpdateAsync(user);
            if (!res)
                return ApiResult.NotOk("修改失败，请刷新页面");
            return ApiResult.Ok();

        }

        public async Task<IApiResult<SysUserEntity>> GetUserInfo(string id)
        {
            ApiResult<SysUserEntity> result = new ApiResult<SysUserEntity>();
            var entity = await _repository.GetAsync(id);
            if (entity == null)
            {
                return result.NotOk("账户不存在");

            }
            return result.Ok(entity);
        }

        public async Task<DataTable> QueryUserDTable()
        {
            List<UserExcelModel> list = await _repository.GetUserInfoExcel();
            if (list.Count <= 0)
                return null;
            //把list转为datatable
            var table= CommonHelper.ListToDataTable<UserExcelModel>(list);
            return table;
        }

        public async Task<IApiResult> ImportData(IFormFile file)
        {
            if (file.Length <= 0)
                return ApiResult.NotOk("请先选择导入文件");

            var ext = Path.GetExtension(file.FileName).ToLower();
            if (ext != ".xls" && ext != ".xlsx")
            {
                return ApiResult.NotOk("文件必须为.xlsx|.xls");
            }

            MemoryStream ms = new MemoryStream();
            file.CopyTo(ms);
            ms.Seek(0, SeekOrigin.Begin);
            //加载
            ExcelHelper.Load(file.FileName, ms);
            ms.Flush();
            ms.Dispose();
            var count = ExcelHelper.GetSheetsCount();
            var num = 0;
            for (int i = 0; i < count; i++)
            {
                string sheetname = ExcelHelper.GetSheetName(i);
                System.Data.DataTable table = ExcelHelper.ExcelToDataTable(sheetname, true);
                if (table == null || table.Rows.Count == 0)
                {
                    continue;
                }
                //插入到数据库
               num+= await _repository.AddDTable(table);
            }
            if (num <= 0)
            {
                return ApiResult.NotOk("导入数据失败,请检查模板");
            }
            return ApiResult.Ok<string>(null,"成功导入"+num+"条数据");
        }

        public async Task<IApiResult> UpdateBasic(UpdateModel_Basic model)
        {

            var entity =await _repository.GetAsync(_loginInfo.UserId);

            var uploadCof = new UploadConfig(_webHostEnvironment.WebRootPath);
            //保存文件
            var result = await _uploadHelper.UploadAsync(model.File, uploadCof, "Avatar");
            if (result.Success)
            {
                entity.HeadPic = result.Data;
            }
            if(model.TrueName.NotNull())
            entity.TrueName = model.TrueName;
            if(model.Remarks.NotNull())
            entity.Remarks = model.Remarks;
            var res = await _repository.UpdateAsync(entity);
            if (!res)
            {
                return ApiResult.NotOk("更新基本信息失败！");
            }
            return ApiResult.Ok();
        }
    }
}